﻿using Blazored.SessionStorage;
using System.Net.Http.Json;
using System.Text.Encodings.Web;
using WhutDoomCheck.Shared;
using WhutDoomCheck.Shared.HttpModels;

namespace WhutDoomCheck.Client.Services
{
    public class TeacherClient
    {
        public TeacherClient(HttpClient http, ISessionStorageService cache)
        { 
            this.http = http;
            this.cache = cache;
        }

        private readonly HttpClient http;
        private readonly ISessionStorageService cache;

        public async Task<bool> Login(string username, string password)
        {
            var resp = await http.PostAsJsonAsync("/api/login/teacher", new { username, password });

            if (resp.StatusCode == System.Net.HttpStatusCode.Unauthorized) return false;

            var result = await resp.Content.ReadFromJsonAsync<Token>();

            await cache.SetItemAsync("AccessToken", result!.AccessToken);
            return true;
        }
        public async Task<IList<RecordReview>> GetRecordReview()
        {
            var token = await cache.GetItemAsync<string>("AccessToken");

            http.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);

            var result = await http.GetFromJsonAsync<IList<RecordReview>>("/Api/Teacher/GetPendingRequests") ?? throw new InvalidCastException();

            return result;
        }

        public async Task<IList<RecordReviewHistory>> GetReviewHistory()
        {
            var token = await cache.GetItemAsync<string>("AccessToken");

            http.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);

            var result = await http.GetFromJsonAsync<IList<RecordReviewHistory>>("/Api/Teacher/GetReviewHistory") ?? throw new InvalidCastException();

            return result;
        }

        /// <summary>
        /// 审批请求
        /// </summary>
        /// <param name="isAccept"></param>
        /// <returns>成功或失败</returns>
        public async Task<bool> ReviewRequest(int requestId, bool isAccept, string reason)
        {
            var token = await cache.GetItemAsync<string>("AccessToken");

            http.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);

            var action = isAccept ? "accept" : "decline";

            var result = await http.GetAsync($"/Api/Teacher/ReviewRequest/{action}?requestId={requestId}&reason={UrlEncoder.Default.Encode(reason)}");

            return result.StatusCode == System.Net.HttpStatusCode.OK;
        }

        public async Task<Stream> GetUnfinishedStudents()
        {
            var token = await cache.GetItemAsync<string>("AccessToken");

            http.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
            var result = await http.GetAsync("/Api/Teacher/ExportUnfinishedStudents", HttpCompletionOption.ResponseContentRead);

            var stream = new MemoryStream();
            await result.Content.CopyToAsync(stream);
            stream.Position = 0;

            return stream;
        }

        public async Task<Stream> GetFinishedStudents()
        {
            var token = await cache.GetItemAsync<string>("AccessToken");

            http.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
            var result = await http.GetAsync("/Api/Teacher/ExportStudents", HttpCompletionOption.ResponseContentRead);

            var stream = new MemoryStream();
            await result.Content.CopyToAsync(stream);
            stream.Position = 0;

            return stream;
        }

    }
}
